<template>
    <div class="container">
        <div class="header">
            <h2>班级管理</h2>
            <el-button type="primary" @click="handleAdd">添加班级</el-button>
        </div>

        <div class="filter-container">
            <el-input v-model="searchQuery" placeholder="搜索班级名称" style="width: 200px; margin-right: 10px;" @input="handleSearch" />
            <el-select 
                v-model="selectedGrade" 
                placeholder="选择年级" 
                style="width: 120px; margin-right: 10px;" 
                @change="handleFilter"
                filterable
                allow-create
            >
                <el-option label="全部年级" value="" />
                <el-option 
                    v-for="grade in gradeOptions" 
                    :key="grade" 
                    :label="grade" 
                    :value="grade" 
                />
            </el-select>
            <el-button type="info" @click="resetFilter">重置筛选</el-button>
        </div>

        <el-table :data="paginatedClassList" border style="width: 100%" v-loading="loading">
            <el-empty v-if="!loading && paginatedClassList.length === 0" description="暂无数据" />
            <el-table-column prop="clazzName" label="班级名称" width="180" sortable />
            <el-table-column label="部门" width="120">
                <template #default="scope">
                    {{ getDepartmentName(scope.row.departmentCode) }}
                </template>
            </el-table-column>
            <el-table-column label="教师" width="120">
                <template #default="scope">
                    {{ getTeacherName(scope.row.teacherId) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
                <template #default="scope">
                    <el-button-group>
                        <el-button size="small" @click="handleEdit(scope.row)" icon="Edit" type="primary">编辑</el-button>
                        <el-button size="small" @click="handleDelete(scope.row.classId)" icon="Delete" type="danger">删除</el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            background
            layout="total, sizes, prev, pager, next"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
            style="margin-top: 20px; text-align: right"
        />

        <!-- 添加/编辑对话框 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="班级名称" prop="clazzName">
                    <el-input v-model="form.clazzName" placeholder="请输入班级名称" />
                </el-form-item>
                <el-form-item label="部门" prop="departmentCode">
                    <el-select v-model="form.departmentCode" placeholder="请选择部门">
                        <el-option
                            v-for="department in departmentList"
                            :key="department.code"
                            :label="department.name"
                            :value="department.code"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="教师" prop="teacherId">
                    <el-select v-model="form.teacherId" placeholder="请选择教师">
                        <el-option
                            v-for="teacher in teacherList"
                            :key="teacher.teacherId"
                            :label="teacher.name"
                            :value="teacher.teacherId"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../api/request.js'

// 数据定义
const classList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加班级')
const formRef = ref(null)
const searchQuery = ref('')
const selectedGrade = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const gradeOptions = ['2023级', '2024级', '2025级', '2026级']
const departmentList = ref([])
const teacherList = ref([])

// 表单数据
const form = reactive({
    clazzId: null,
    clazzName: '',
    departmentCode: '',
    teacherId: ''
})

// 表单验证规则
const rules = {
    clazzName: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
    departmentCode: [{ required: true, message: '请输入部门代码', trigger: 'blur' }],
    teacherId: [{ required: true, message: '请输入教师ID', trigger: 'blur' }]
}

// 计算属性
const filteredClassList = computed(() => {
    let result = classList.value

    // 模糊匹配班级名称
    if (searchQuery.value) {
        result = result.filter(item => 
            item.clazzName.toLowerCase().includes(searchQuery.value.toLowerCase())
        )
    }

    // 过滤年级
    if (selectedGrade.value) {
        result = result.filter(item => item.grade === selectedGrade.value)
    }

    console.log('过滤后的班级数据:', result)  // 添加调试日志
    return result
})

const paginatedClassList = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return filteredClassList.value.slice(start, end)
})

const total = computed(() => filteredClassList.value.length)

// 生命周期钩子
onMounted(async () => {
    await fetchDepartments()  // 先获取部门数据
    await fetchTeachers()     // 再获取教师数据
    await fetchClasses()      // 最后获取班级数据
})

// 方法定义
const fetchClasses = async () => {
    loading.value = true
    try {
        const res = await api.class.getAll()
        console.log('获取班级数据:', res)
        if (res.code === 1) {
            classList.value = res.data
        } else {
            ElMessage.error('获取班级列表失败')
        }
    } catch (error) {
        console.error('获取班级列表出错:', error)
        ElMessage.error('获取班级列表失败')
    } finally {
        loading.value = false
    }
}

const handleAdd = () => {
    dialogTitle.value = '添加班级'
    form.clazzId = null
    form.clazzName = ''
    form.departmentCode = ''
    form.teacherId = ''
    dialogVisible.value = true
}

const handleEdit = (row) => {
    dialogTitle.value = '编辑班级'
    Object.assign(form, row)
    dialogVisible.value = true
}

const handleDelete = (clazzId) => {
    ElMessageBox.confirm('确定要删除该班级吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await api.class.delete(clazzId)
            if (res.code === 1) {
                ElMessage.success('删除成功')
                fetchClasses()
            } else {
                ElMessage.error(res.msg || '删除失败')
            }
        } catch (error) {
            console.error('删除班级出错:', error)
            ElMessage.error('删除失败')
        }
    }).catch(() => {})
}

const submitForm = async () => {
    if (!formRef.value) return

    formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                let res
                const postData = {
                    clazzName: form.clazzName,
                    departmentCode: form.departmentCode,
                    teacherId: form.teacherId
                }
                if (form.clazzId) {
                    postData.clazzId = form.clazzId
                    res = await api.class.update(postData)
                } else {
                    res = await api.class.add(postData)
                }
                if (res.code === 1) {
                    ElMessage.success(form.clazzId ? '更新成功' : '添加成功')
                    dialogVisible.value = false
                    fetchClasses()
                } else {
                    ElMessage.error(res.msg || (form.clazzId ? '更新失败' : '添加失败'))
                }
            } catch (error) {
                console.error(error)
                ElMessage.error(form.clazzId ? '更新失败' : '添加失败')
            }
        }
    })
}

const handleSearch = () => {
    currentPage.value = 1
}

const handleFilter = () => {
    currentPage.value = 1
    console.log('选择年级:', selectedGrade.value)  // 添加调试日志
}

const resetFilter = () => {
    searchQuery.value = ''
    selectedGrade.value = null
    currentPage.value = 1
}

const handleSizeChange = (newSize) => {
    pageSize.value = newSize
    currentPage.value = 1
}

const handlePageChange = (newPage) => {
    currentPage.value = newPage
}

const getDepartmentName = (code) => {
    const department = departmentList.value.find(d => d.code === code)
    return department ? department.name : '未知部门'
}

const fetchDepartments = async () => {
    try {
        const res = await api.department.getAll()
        console.log('获取部门数据:', res)  // 添加调试日志
        if (res.code === 1) {
            departmentList.value = res.data
        } else {
            ElMessage.error('获取部门列表失败')
        }
    } catch (error) {
        console.error('获取部门列表出错:', error)
        ElMessage.error('获取部门列表失败')
    }
}

const fetchTeachers = async () => {
    try {
        const res = await api.teacher.getAll()
        console.log('获取教师数据:', res)  // 添加调试日志
        if (res.code === 1) {
            teacherList.value = res.data
        } else {
            ElMessage.error('获取教师列表失败')
        }
    } catch (error) {
        console.error('获取教师列表出错:', error)
        ElMessage.error('获取教师列表失败')
    }
}

const getTeacherName = (teacherId) => {
    if (!teacherId) return '未分配教师'  // 处理空值
    const teacher = teacherList.value.find(t => t.teacherId === teacherId)
    return teacher ? teacher.name : '未知教师'
}
</script>

<style scoped>
.container {
    padding: 20px;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.filter-container {
    margin-bottom: 20px;
}
</style>